import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 此处类的属性的名字，要和 JSON 的 key 保持一致
class Student {
    public int classId;
    public int studentId;
}

@WebServlet("/studentInfo")
public class StudentInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String queryString = req.getQueryString();
        System.out.println(queryString);

        String classId = req.getParameter("classId");
        String studentId = req.getParameter("studentId");
        System.out.println("classId: " + classId + " studentId: " + studentId);
        resp.getWriter().write("classId: " + classId + " studentId: " + studentId);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.setContentType("text/html; charset=utf8");
//        String classId = req.getParameter("classId");
//        String studentId = req.getParameter("studentId");
//        System.out.println("classId: " + classId + " studentId: " + studentId);
//        resp.getWriter().write("classId: " + classId + " studentId: " + studentId);

        // 处理 JSON 格式的请求
        ObjectMapper objectMapper = new ObjectMapper();
        // JSON类型字符串转成类
        Student student = objectMapper.readValue(req.getInputStream(), Student.class);
        System.out.println(student.classId + ", " + student.studentId);
        resp.getWriter().write(student.classId + ", " + student.studentId);
    }
}
